package com.gmscosmo.janus.sendMessage;

import cn.wildfirechat.sdk.ChatConfig;
import cn.wildfirechat.sdk.MavAdmin;
import com.alibaba.fastjson.JSONObject;
import com.gmscosmo.janus.util.JanusLogUtil;
import com.gmscosmo.janus.util.Utils;
import com.gmscosmo.model.Event;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author stephen.qiu
 */
@Component
public class IMSender extends Sender {
    private boolean ok = false;

    @PostConstruct
    private void init() {
        if (Utils.isNotEmpty(imConfig.getAdmin_url())) {
            janusLogUtil.log("初始化IM SDK", this.getClass(), JanusLogUtil.TRACE);
            ChatConfig.initAdmin(imConfig.getAdmin_url(), imConfig.getAdmin_secret());
            ok = true;
        } else {
            janusLogUtil.log("缺失IM SDK URL", this.getClass(), JanusLogUtil.TRACE);
        }
    }

    @Override
    public void sendEventToListener(String userId, JSONObject data) {
        if (!ok) {
            return;
        }
        if (userId == null) {
            janusLogUtil.log("sendEventToListener userId is null data " + data, this.getClass(), JanusLogUtil.ERROR);
            return;
        }
        try {
            MavAdmin.mavSignalLaunch(userId, data.toJSONString());
        } catch (Exception e) {
            janusLogUtil.log("IM Sender failed", this.getClass(), JanusLogUtil.TRACE);
        }
    }

    @Override
    public void sendEvent(String userId, Event event) {
        if (!ok) {
            return;
        }
        if (userId == null) {
            janusLogUtil.log("sendEvent userId is null data " + event, this.getClass(), JanusLogUtil.ERROR);
            return;
        }
        try {
            MavAdmin.mavSignalLaunch(userId, JSONObject.toJSONString(event));
        } catch (Exception e) {
            janusLogUtil.log("IM Sender failed", this.getClass(), JanusLogUtil.TRACE);
        }
    }
}
